/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package servlet.ajax;

import classes.*;
import database.database;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import logic.Main;

/**
 *
 * @author Shelling Ford
 */
@WebServlet(name="command", urlPatterns={"/ajax/command"})
public class command extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        HttpSession session = request.getSession(true);

        int status = 0;
        String message = "default";
        User executor = (User)session.getAttribute("user");

        String command = request.getParameter("command");
        String param1 = request.getParameter("param1");
        String param2 = request.getParameter("param2");
        String type = request.getParameter("type");
        String name = request.getParameter("name");

        User sysSender = new User();
        sysSender.username = "[ChatOK System]";

        if (command.equalsIgnoreCase("/exit")) {
            Message pesan;
            if (type.equalsIgnoreCase("room")) {
                if (!name.equalsIgnoreCase("home")) {
                    Room recipientRoom = Main.getRoomFromName(name);
                    recipientRoom.userInRoom.remove(executor);
                    if (recipientRoom.userInRoom.isEmpty()) {
                        if (!recipientRoom.persist) {
                            Main.roomList.remove(recipientRoom);
                        }
                        else {
                            pesan = new Message(sysSender,recipientRoom,executor.username+" has left the room voluntary!");
                            Main.addMessage(pesan);
                        }
                    }
                    else {
                        if (recipientRoom.owner == executor) {
                            recipientRoom.owner = recipientRoom.userInRoom.get(0);
                        }
                        pesan = new Message(sysSender,recipientRoom,executor.username+" has left the room voluntary!");
                        Main.addMessage(pesan);
                    }
                    status = 1;
                    message = "Exit Success!!!";
                }
            }
            else {
                User recipientUser = Main.getUserFromName(name);
                pesan = new Message(executor,recipientUser,"Sorry, I left you :3");
                Main.addMessage(pesan);
                status = 1;
                message = "Exit Success!!!";
            }
        }
        else if (command.equalsIgnoreCase("/info")) {
            String roomName;
            status = 1;
            if (param1.isEmpty()) {
                roomName = name;
            }
            else {
                roomName = param1;
            }
            System.out.println(roomName);
            if (!roomName.equalsIgnoreCase("home")) {
                Room infoRoom = Main.getRoomFromName(roomName);
                User infoUser = Main.getUserFromName(roomName);
                if (infoRoom != null) {
                    message = "Info Room :\nName = "+infoRoom.name+"\nOwner = "+infoRoom.owner.username+"\nCategory ID = "+infoRoom.place+"\nPersistence = "+infoRoom.persist;
                }
                else if (infoUser != null) {
                    message = "Info User :\nUsername = "+infoUser.username+"\nFull Name = "+infoUser.nama+"\nPrivillege = "+infoUser.privilege;
                }
                else {
                    message = "User/Room not found!";
                }
            }
            else {
                message = "Info Home : Room home is owned by [ChatOK System]";
            }
        }
        else if (command.equalsIgnoreCase("/create")) {
            database db = new database();
            if (Main.getRoomFromName(param1) == null && Main.getOwnedRoom(executor)<db.getMaxRoom()) {
                status = 1;

                Room createdRoom;
                if (param2.isEmpty()) {
                    createdRoom = new Room(param1,0,executor);
                }
                else {
                    createdRoom = new Room(param1,Integer.parseInt(param2),executor);
                }
                createdRoom.userInRoom.add(executor);
                Main.roomList.add(createdRoom);

                type = "room";
                name = createdRoom.name;
                message = "Room created!";
            }
            else {
                message = "Create room FAIL!";
            }
        }
        else if (command.equalsIgnoreCase("/join")) {
                status = 1;
                Room recipientRoom = Main.getRoomFromName(param1);
                if (recipientRoom != null) {
                    recipientRoom.userInRoom.add(executor);
                    Main.addMessage(new Message(sysSender,recipientRoom,executor.username+" joined the room!"));
                    type = "room";
                    name = param1;
                    message = "Join Success!";
                }
                else {
                    message = "fail";
                }
        }
        else if (command.equalsIgnoreCase("/chat")) {
            status = 1;
            if (Main.getUserFromName(param1) != null && !param1.equalsIgnoreCase(executor.username)) {
                type = "user";
                name = param1;
                message = "Chat with "+param1;
            }
            else {
                message = "fail";
            }
        }
        else if (command.equalsIgnoreCase("/addfriend")) {
            if (Main.getUserFromName(param1) != null) {
                database db = new database();
                db.addFriend(executor.username, param1);
                status = 1;
                message = "Add friend success!!!";
            }
        }
        // khusus momod dan mimin
        else if (command.equalsIgnoreCase("/kick")) {
            // ntar
        }
        else if (command.equalsIgnoreCase("/ban")) {
            if (Main.getUserFromName(param1) != null && executor.privilege.equalsIgnoreCase("moderator")) {
                database db = new database();
                db.banUser(param1, true);
                status = 1;
                message = param1+" Banned!!!";
            }
        }
        else if (command.equalsIgnoreCase("/unban")) {
            if (Main.getUserFromName(param1) != null && executor.privilege.equalsIgnoreCase("moderator")) {
                database db = new database();
                db.banUser(param1, false);
                status = 1;
                message = param1+" Unbanned!!!";
            }
        }
        else if (command.equalsIgnoreCase("/persist")) {
            if (Main.getRoomFromName(name) != null && executor.privilege.equalsIgnoreCase("moderator")) {
                if (param1.equalsIgnoreCase("on")) {
                    Main.getRoomFromName(name).persist = true;
                    status = 1;
                    message = "Persistence Changed!!!";
                }
                else if (param1.equalsIgnoreCase("off")) {
                    Main.getRoomFromName(name).persist = false;
                    status = 1;
                    message = "Persistence Changed!!!";
                }
            }
        }
        else if (command.equalsIgnoreCase("/setowner")) {
            if (Main.getRoomFromName(name) != null && executor.privilege.equalsIgnoreCase("moderator")) {
                if (Main.getUserFromName(param1) != null) {
                    Main.getRoomFromName(name).owner = Main.getUserFromName(param1);
                    status = 1;
                    message = param1 + " is now OWNING";
                }
            }
        }

        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            out.println("<?xml version=\"1.0\"?>");
            out.println("<root>");
            out.println("<command>"+command+"</command>");
            out.println("<status>"+status+"</status>");
            out.println("<type>"+type+"</type>");
            out.println("<name>"+name+"</name>");
            out.println("<content>"+message+"</content>");
            out.println("</root>");
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
